<script setup>
import { Modal } from 'ant-design-vue'
import { DownOutlined, DownloadOutlined, LoginOutlined, PlusOutlined, ReloadOutlined, SearchOutlined, SettingOutlined, UpOutlined } from '@ant-design/icons-vue'
import { getBillList, rebuildBill } from '~@/api/card/index'

defineOptions({
  name: 'Bill',
})
const userStore = useUserStore()
const { hasPermission } = userStore
const statusMap = {
  0: '关闭',
  1: '运行中',
  2: '上线',
  3: '错误',
}
const message = useMessage()
const columns = shallowRef([
  {
    title: '账单日期',
    align: 'left',
    dataIndex: 'billDate',
    width: 150,
  },
  {
    title: '账单名称',
    dataIndex: 'billName',
    width: 250,
  },
  {
    title: '账单类型',
    dataIndex: 'billType',
    width: 120,
  },

  {
    title: '状态',
    dataIndex: 'status',
    align: 'center',
    width: 120,

  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
    width: 200,
  },

  {
    title: '操作',
    dataIndex: 'action',
    align: 'center',
    fixed: 'right',
    width: 150,

  },
])
const billOptions = shallowRef([
  { configKey: '', configValue: '全部' },
  { configKey: 'CARD_EXPENSE', configValue: '消费明细' },
  { configKey: 'CARD_RECHARGE', configValue: '充值明细' },
])
const loading = shallowRef(false)
const totalNum = shallowRef(0)
const pagination = reactive({
  pageSize: 8,
  pageSizeOptions: ['10', '20', '30', '40'],
  current: 1,
  total: totalNum,
  showSizeChanger: true,
  // showQuickJumper: true,
  showTotal: total => `总共：${total}`,
  onChange(current, pageSize) {
    pagination.pageSize = pageSize
    pagination.current = current
    init()
  },
})
const dataSource = shallowRef([])
const formModel = reactive({
  billType: void 0,
  cardDate: void 0,
})
const staticInfo = reactive({
  cardCount: void 0,
  refundAmount: void 0,
  defrayAmount: void 0,
  balance: void 0,
  withdrawAmount: void 0,
  rechargeAmount: void 0,
})
const tableSize = ref(['large'])
const open = ref(false)
const options = computed(() => {
  return columns.value.map((item) => {
    if (item.dataIndex === 'action') {
      return {
        label: item.title,
        value: item.dataIndex,
        disabled: true,
      }
    }
    return {
      label: item.title,
      value: item.dataIndex,
    }
  })
})
const dropdownVisible = ref(false)
const getCheckList = computed(() => columns.value.map(item => item.dataIndex))
const state = reactive({
  indeterminate: false,
  checkAll: true,
  checkList: getCheckList.value,
})
onMounted(() => {
  formModel.billType = billOptions.value[0].configKey
  init()
})
// 处理状态
function handleStatus(text) {
  switch (text) {
    case 'INIT':
      return '待创建'
    case 'SUCCESS':
      return '成功'
    default:
      return '失败'
  }
}
// 查询账单列表
async function init() {
  if (loading.value)
    return
  loading.value = true
  try {
    const startDate = formModel.cardDate?.[0]?.format('YYYY-MM-DD')
    const endDate = formModel.cardDate?.[1]?.format('YYYY-MM-DD')
    const { data } = await getBillList({
      param: { ...formModel, startDate, endDate },
      page: {
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },

    })

    dataSource.value = data.data ?? []
    // dataSource.value = data.data ?? []
    totalNum.value = data.pageInfo.total
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}
async function onSearch() {
  pagination.current = 1
  await init()
}

// 重新生成
async function getRebill(record) {
  if (loading.value)
    return
  loading.value = true
  try {
    const { data } = await rebuildBill(record.id)
    message.success('操作成功')
    init()
  }
  catch (e) {
    console.log(e)
  }
  finally {
    loading.value = false
  }
}

// 重置查询参数
async function onReset() {
  formModel.billType = void 0
  formModel.cardDate = void 0
  await init()
}
// 下载
function handleDownload(record) {
  if (record.ossUrl) {
    window.location.href = record.ossUrl
  }
}

function handleSizeChange(e) {
  tableSize.value[0] = e.key
}
function filterAction(value) {
  return columns.value.filter((item) => {
    if (value.includes(item.dataIndex))
      return true

    return false
  })
}
const filterColumns = ref(filterAction(getCheckList.value))
function handleCheckAllChange(e) {
  Object.assign(state, {
    checkList: e.target.checked ? getCheckList.value : [],
    indeterminate: true,
  })
  filterColumns.value = e.target.checked ? filterAction(getCheckList.value) : filterColumns.value.filter(item => item.dataIndex === 'action')
}
watch(
  () => state.checkList,
  (val) => {
    state.indeterminate = !!val.length && val.length < getCheckList.value.length
    state.checkAll = val.length === getCheckList.value.length
  },
)
function handleResetChange() {
  state.checkList = getCheckList.value
  filterColumns.value = filterAction(getCheckList.value)
}
function handleCheckChange(value) {
  const filterValue = filterAction(value)
  filterColumns.value = filterValue
}
const expand = ref(false)
</script>

<template>
  <page-container>
    <div>
      <a-card mb-4>
        <a-form :model="formModel" layout="inline">
          <a-form-item name="cardDate" label="账单日期" style="margin-bottom:20px;">
            <a-range-picker v-model:value="formModel.cardDate" style="width:220px;" allow-clear />
          </a-form-item>
          <a-form-item name="billType" label="账单类型" style="margin-bottom:20px;">
            <a-select v-model:value="formModel.billType" style="width:180px;" placeholder="请选择" allow-clear>
              <a-select-option v-for="item in billOptions" :key="item.configKey" :value="item.configKey">
                {{ item.configValue }}
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item>
            <a-space flex w-full>
              <a-button type="primary" @click="onSearch">
                <SearchOutlined />查询
              </a-button>
              <a-button @click="onReset">
                重置
              </a-button>
            </a-space>
          </a-form-item>
        </a-form>
      </a-card>

      <a-card>
        <a-table bordered :loading="loading" :columns="filterColumns" :scroll="{ x: 1000 }" :data-source="dataSource" :pagination="pagination">
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'balance'">
              <span :style="{ color: record.balance < 0 ? 'red' : 'black' }">{{ Number(record.balance).toFixed(2) }}</span>
            </template>

            <template v-else-if="column.dataIndex === 'status'">
              {{ handleStatus(record.status) }}
            </template>
            <template v-else-if="column.dataIndex === 'billType'">
              {{ record.billType === 'CARD_EXPENSE' ? '消费明细' : '充值明细' }}
            </template>

            <template v-else-if="column.dataIndex === 'action'">
              <div class="action flex flex-center">
                <a-button v-if="record.status === 'SUCCESS'" type="link" class="ml-2" @click="handleDownload(record)">
                  <DownloadOutlined />下载
                </a-button>
                <span v-else-if="record.status === 'INIT'">--</span>
                <a-button v-else type="link" class="ml-2" @click="getRebill(record)">
                  <LoginOutlined />重新生成
                </a-button>
              </div>
            </template>
          </template>
        </a-table>
      </a-card>
    </div>
  </page-container>
</template>

  <style lang="less" scoped>
.red{
      color:red;
      /* color:#ff4d4f; */
    }
    .card-title{
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      flex: auto;
      color: rgba(0, 0, 0, 0.88);
      font-weight: 600;
      font-size: 16px;
      line-height: 1.5;
    }
  @media screen and (max-width: 1200px) and (min-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      margin-left: -44px;
      .statItem {
        padding: 0 16px;
      }
    }
  }

  @media screen and (max-width: 992px) {
    .activeCard {
      margin-bottom: 24px;
    }
    .members {
      margin-bottom: 0;
    }
    .extraContent {
      float: none;
      margin-right: 0;
      .statItem {
        padding: 0 16px;
        text-align: left;
        &::after {
          display: none;
        }
      }
    }
  }

  @media screen and (max-width: 768px) {
    .extraContent {
      margin-left: -16px;
    }
    .projectList {
      .projectGrid {
        width: 50%;
      }
    }
  }

  @media screen and (max-width: 576px) {
    .pageHeaderContent {
      display: block;
      .content {
        margin-left: 0;
      }
    }
    .extraContent {
      .statItem {
        float: none;
      }
    }
  }

  @media screen and (max-width: 480px) {
    .projectList {
      .projectGrid {
        width: 100%;
      }
    }
  }
  </style>
